package com.sengled.cloud.biz.union.mgt.service.sys.impl;

import com.sengled.cloud.biz.union.mgt.common.SysConstants;
import com.sengled.cloud.biz.union.mgt.dao.sys.*;
import com.sengled.cloud.biz.union.mgt.model.dto.UnionUser;
import com.sengled.cloud.biz.union.mgt.model.po.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by ti on 2017/11/6.
 */
public class CustomUserService implements UserDetailsService {
    @Autowired
    private UserAccountDao userAccountDao;
    @Autowired
    private RoleModulePermissionDao roleModulePermissionDao;
    @Autowired
    private AccountRoleDao accountRoleDao;
    @Autowired
    private ShopAccountDao shopAccountDao;
    @Autowired
    private ShopAccountModuleDao shopAccountModuleDao;
    @Override
    public UnionUser loadUserByUsername(String username) { //重写loadUserByUsername 方法获得 userdetails 类型用户

       /* List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        return new org.springframework.security.core.userdetails.User("test","123456", authorities);*/

       //根据-#-拆分username ，全面是channel后面是username;
        String name = "";
        String pwd = "";
        Long accountId = 0L;
        String channel = username.split("-#-")[0];
        username = username.split("-#-")[1];
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<String> grantedAuthStrList = new ArrayList<String>();
        if(SysConstants.CHANNEL_PAD.equals(channel)){
            ShopAccount shopAccount = shopAccountDao.selectByUsername(username);
            if(shopAccount == null){
                throw new UsernameNotFoundException("用户名不存在");
            }else{
                accountId = shopAccount.getId();
                name = shopAccount.getShopName();
                pwd = shopAccount.getAccountPwd();
                //查询与shopaccount关联的module;
                List<ShopAccountModule> shopAccountModules = shopAccountModuleDao.selectShopAccountModuleList(accountId);
                if(CollectionUtils.isNotEmpty(shopAccountModules)){
                    shopAccountModules.forEach(shopAccountModule -> {
                        grantedAuthStrList.add("ROLE_" + shopAccountModule.getModuleId());
                    });
                }
                return new UnionUser(accountId, name, pwd, true,authorities);
            }
        }else{
            UserAccount userAccount = userAccountDao.selectByUsername(username);
            if(userAccount == null){
                throw new UsernameNotFoundException("用户名不存在");
            }else{
                accountId = userAccount.getId();
                name = userAccount.getAccountName();
                pwd = userAccount.getAccountPwd();


                //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
                List<AccountRole> roles = accountRoleDao.selectByUserAccountKey(accountId);
                //通过用户账号id获取角色Id列表
                List<Long> roleIds = roles.stream().map(AccountRole :: getRoleId).collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(roleIds)){
                //通过角色Id列表，批量获取用户对应模块和权限
                    List<RoleModulePermission> roleModulePermissions = roleModulePermissionDao.selectByRolesKey(roleIds);
                    if(CollectionUtils.isNotEmpty(roleModulePermissions)){
                        //按模块ID分组
                        Map<Long,List<RoleModulePermission>> mpMap = roleModulePermissions.stream().collect(Collectors.groupingBy(i -> i.getModuleId()));

                        mpMap.forEach((k,v) -> {
                            //对应模块的权限LIST去重
                            List<Long> pl = v.stream().map(RoleModulePermission :: getPermissionId).distinct().collect(Collectors.toList());
                            pl.forEach(l -> {
                                //把模块ID和权限ID组合拼接作为权限表示
                                grantedAuthStrList.add("ROLE_" + k +"_"+l);
                            });
                        });
                        for(String s:grantedAuthStrList)
                        {
                            authorities.add(new SimpleGrantedAuthority(s));
                            //System.out.println(role.getName());
                        }
                    }

                }

//        return new org.springframework.security.core.userdetails.User(userAccount.getAccountName(),
//                userAccount.getAccountPwd(), authorities);
                return new UnionUser(accountId, name, pwd, true,authorities);
            }
        }



    }
}
